package com.gaokao.demo.service;


import com.gaokao.demo.constants.Constant;
import com.gaokao.demo.entity.SysRole;
import com.gaokao.demo.entity.SysUser;
import com.gaokao.demo.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.ArrayList;
import java.util.List;

public class CustomUserService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws AuthenticationException {
        SysUser user = sysUserMapper.findUserByUserName(s);
        if (user != null) {
            if (user.getStatus() == null || user.getStatus().equals(Constant.USER_STATUS_INACTIVE)) {
                throw new DisabledException(s + "用户未激活！");
            }
            List<SysRole> sysRoleList = user.getSysRoleList();//获取用户角色
            List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();//权限列表
            for (SysRole sysRole : sysRoleList) {
                if (sysRole != null && sysRole.getName() != null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysRole.getName());
                    grantedAuthorityList.add(grantedAuthority);
                }
            }
            return new User(user.getUsername(), user.getPassword(), grantedAuthorityList);

        }else {
            throw new InternalAuthenticationServiceException(s+"用户不存在！");
        }
    }
}
